﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Commlibrary;
using System.Threading;
using System.Collections;

namespace StockAssistant
{
    public partial class frmAssistant : Form
    {
        private enum COL_STOCK : int
        {
            COL_STOCK_NO = 0,
            COL_SUM,
            COL_PRICE,
            COL_BUY_TIME,
            COL_CURRENT_PRICE,
            COL_PROFIT
        }

        #region 委托方法定义
        // 委托
        public delegate void DelegateFindProfit(String sStockNo, String sCurrPrice, String sProfit);
        #endregion

        private Icon mNetTrayIcon = new Icon("stock32.ico");
        private DS_Stock m_dsStock = null;
        private Boolean bExist = false;
        // 委托实例
        public DelegateFindProfit m_delegateFindProfit;
        // 监控进程
        private CommLibrary.ThreadItem m_threadItemMonit;

        public frmAssistant()
        {
            InitializeComponent();

            this.m_dsStock = new DS_Stock();
            // 初始化委托
            this.m_delegateFindProfit = new DelegateFindProfit(this.FindProfit);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmAddStock frmAdd = new frmAddStock();
            frmAdd.m_dsStock = this.m_dsStock;

            if (DialogResult.OK == frmAdd.ShowDialog())
            {
                int iSerial = 1;
                if (this.m_dsStock == null)
                    this.m_dsStock = new DS_Stock();

                if (this.m_dsStock.T_USER_STOCK.Rows.Count > 0)
                {
                    DS_Stock.T_USER_STOCKRow rowFind =
                        (DS_Stock.T_USER_STOCKRow)this.m_dsStock.T_USER_STOCK.Rows[
                            this.m_dsStock.T_USER_STOCK.Rows.Count - 1];
                    iSerial = rowFind.SERIAL + 1;
                }

                DS_Stock.T_USER_STOCKRow rowNew = 
                    this.m_dsStock.T_USER_STOCK.NewT_USER_STOCKRow();
                rowNew.SERIAL = iSerial;
                rowNew.UID = "QH";
                rowNew.STOCK_NO = frmAdd.sStockNo;
                rowNew.STOCK_NAME = frmAdd.sStockName;
                rowNew.BUY_TIME = DateTime.Parse(frmAdd.sBuyTime);
                rowNew.BUY_POS = "";
                rowNew.BUY_NUM = int.Parse(frmAdd.sBuyNum);
                rowNew.BUY_PRICE = Decimal.Parse(frmAdd.sPrice);
                this.m_dsStock.T_USER_STOCK.Rows.Add(rowNew);

                this.addStockInfoOneRow(rowNew);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.m_dsStock.WriteXml(Const.T_USER_STOCK_XML);
            bExist = true;
            this.Close();
        }

        private void frmAssistant_Shown(object sender, EventArgs e)
        {
            notIco.Icon = mNetTrayIcon;
            int x = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Size.Width - this.Width;
            int y = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Size.Height - this.Height;
            this.SetDesktopLocation(x, y);
            this.Hide();
        }

        private void frmAssistant_Deactivate(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void notIco_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.BringToFront();
            this.Focus();
            this.Activate();
        }

        private void frmAssistant_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!bExist)
            {
                e.Cancel = true;
                this.Hide();
            }
        }
         
        private void btnStart_Click(object sender, EventArgs e)
        {
            this.StartThreadMonit();
        }

        private void frmAssistant_Load(object sender, EventArgs e)
        {
            try
            {
                this.m_dsStock.ReadXml(Const.T_USER_STOCK_XML);

                if (this.m_dsStock.T_USER_STOCK.Rows.Count > 0)
                { 
                    foreach (DataRow drLoop in this.m_dsStock.T_USER_STOCK.Rows)
                    {
                        this.addStockInfoOneRow((DS_Stock.T_USER_STOCKRow) drLoop);
                    }
                    
                }
            }
            catch { 
            
            }
        }

        private void addStockInfoOneRow(DS_Stock.T_USER_STOCKRow rowFind)
        {
            this.lstStockInfo.Items.Add(rowFind.STOCK_NO);
            this.lstStockInfo.Items[
                this.lstStockInfo.Items.Count - 1].SubItems.Add(rowFind.BUY_NUM.ToString());
            this.lstStockInfo.Items[
                this.lstStockInfo.Items.Count - 1].SubItems.Add(rowFind.BUY_PRICE.ToString());
            this.lstStockInfo.Items[
                this.lstStockInfo.Items.Count - 1].SubItems.Add(rowFind.BUY_TIME.ToString("yyyy/MM/dd HH:mm:ss"));
            this.lstStockInfo.Items[
                this.lstStockInfo.Items.Count - 1].SubItems.Add("");
            this.lstStockInfo.Items[
                this.lstStockInfo.Items.Count - 1].SubItems.Add("");
        }

        private void FindProfit(String sStockNo, String sCurrPrice, String sProfit)
        {
            if (this.lstStockInfo.Items.Count > 0)
            { 
                foreach (ListViewItem stockItem in this.lstStockInfo.Items)
                {
                    if (stockItem.Text.Equals(sStockNo))
                    {
                        stockItem.SubItems[(int)COL_STOCK.COL_CURRENT_PRICE].Text = sCurrPrice;
                        stockItem.SubItems[(int)COL_STOCK.COL_PROFIT].Text = sProfit;
                        break;
                    }
                }
            }
        }

        private void StartThreadMonitMethod()
        {
            ManualResetEvent eventStop = this.m_threadItemMonit.GetEventStop();
            ManualResetEvent eventStopped = this.m_threadItemMonit.GetEventStopped();

            ArrayList arrStockInfo = new ArrayList();

            if (this.m_dsStock.T_USER_STOCK.Rows.Count > 0)
            {
                foreach (DataRow drLoop in this.m_dsStock.T_USER_STOCK.Rows)
                {
                    DS_Stock.T_USER_STOCKRow drStock = (DS_Stock.T_USER_STOCKRow)drLoop;

                    CStockInfo stockInfo = new CStockInfo();
                    stockInfo.sStockNo = drStock.STOCK_NO;
                    stockInfo.sStockNm = drStock.STOCK_NAME;
                    stockInfo.iStockBuyNum = drStock.BUY_NUM;
                    stockInfo.dStockBuyPrice = drStock.BUY_PRICE;
                    stockInfo.dtStockBuyTime = drStock.BUY_TIME;
                    arrStockInfo.Add(stockInfo);
                }
            }

            // 邮件监控进程类
            StockMonitThread oMailMonitThread =
                new StockMonitThread(
                    eventStop,
                    eventStopped,
                    arrStockInfo,
                    this);
            // 启动邮件监控进程
            oMailMonitThread.Run();
        }

        private void StartThreadMonit()
        {
            // 重设事件
            ManualResetEvent eventMonitStop = new ManualResetEvent(false);
            ManualResetEvent eventMonitStoped = new ManualResetEvent(false);
            // 重设标志位
            eventMonitStop.Reset();
            eventMonitStoped.Reset();
            // 创建监控进程
            Thread oMonitThread = new Thread(new ThreadStart(this.StartThreadMonitMethod));
            // 设置进程名字
            oMonitThread.Name = "";
            // 保存进程
            this.m_threadItemMonit =
                new CommLibrary.ThreadItem(oMonitThread, eventMonitStop, eventMonitStoped);
            // 启动进程
            oMonitThread.Start();
        }

        /// <summary>
        /// 停止邮件监控进程
        /// </summary>
        private void StopThreadMail()
        {
            // 获得进程
            Thread oMonitThread = this.m_threadItemMonit.GetThread();
            // 获得事件-(主进程设置该事件表明子进程被终止)
            ManualResetEvent eventStop = this.m_threadItemMonit.GetEventStop();
            // 获得事件-(子进程设置该事件当子进程被终止时)
            ManualResetEvent eventStopped = this.m_threadItemMonit.GetEventStopped();

            // 进程在运行中
            if (oMonitThread != null && oMonitThread.IsAlive)
            {
                // 停止进程
                eventStop.Set();

                // 等待进程被终止
                while (oMonitThread.IsAlive)
                {
                    // 等待进程(防止死锁)
                    if (WaitHandle.WaitAll(
                        (new ManualResetEvent[] { eventStopped }),
                        100,
                        true))
                    {
                        break;
                    }
                    // 处理消息队列的Windows消息
                    System.Windows.Forms.Application.DoEvents();
                }
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.StopThreadMail();
        }
    }
}
